package com.ailot.cloud.upms.api.datasource;

import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Author : litao
 * @create 2023/12/7 10:58
 */
@Slf4j
@Service
@AllArgsConstructor
public class DynamicDataSourceService {


    //    private final DynamicRoutingDataSource dynamicRoutingDataSource;
    private final DataSourceCreator druidDataSourceCreator;

    /**
     * 添加数据源
     *
     * @param dataSourceProperty
     */
    public void addDataSource(DataSourceProperty dataSourceProperty) {
        DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
//        dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
    }

    public void removeDataSource(String ds) {
//        dynamicRoutingDataSource.removeDataSource(ds);
    }

    public void checkDataSource(DataSourceProperty dataSourceProperty) {
        try {
            DriverManager.getConnection(dataSourceProperty.getUrl(), dataSourceProperty.getUsername(), dataSourceProperty.getPassword());
        } catch (SQLException e) {
            throw new RuntimeException("连接失败：" + e.getMessage());
        }
    }

}
